/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */
package es.silenus.detecta.controller;

import es.silenus.detecta.Constants;

import es.silenus.detecta.dao.KnowledgeUnitDAO;
import es.silenus.detecta.dao.Page;
import es.silenus.detecta.dao.QualificationDAO;

import es.silenus.detecta.model.KnowledgeUnit;
import es.silenus.detecta.model.Organization;
import es.silenus.detecta.model.Qualification;
import es.silenus.detecta.model.User;

import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Qualification controller.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 08-abr-2009 11:03:52
 */
public class QualificationController extends BaseController {
	/**
	 * The qualification DAO.
	 */
	private QualificationDAO qualificationDAO;

	/**
	 * The knowledge unit DAO.
	 */
	private KnowledgeUnitDAO knowledgeUnitDAO;

	/**
	 * Sets the qualication DAO.
	 *
	 * @param qualificationDAO the qualication DAO.
	 */
	public void setQualificationDAO(final QualificationDAO qualificationDAO) {
		this.qualificationDAO = qualificationDAO;
	}

	/**
	 * Sets the knowledge unit DAO.
	 *
	 * @param knowledgeUnitDAO the knowledge unit DAO.
	 */
	public void setKnowledgeUnitDAO(final KnowledgeUnitDAO knowledgeUnitDAO) {
		this.knowledgeUnitDAO = knowledgeUnitDAO;
	}

	/**
	 * Finds qualifications.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String findQualifications(final HttpServletRequest request, final HttpServletResponse response) {
		User current = getUser(request);

		Map<String, Object> sample = new HashMap<String, Object>();
		String temp = request.getParameter("id");

		if(temp != null) {
			sample.put("id", temp);
		}

		temp = request.getParameter("code");

		if(temp != null) {
			sample.put("code", temp);
		}

		temp = request.getParameter("description");

		if(temp != null) {
			temp = StringUtils.replaceChars(temp, CharUtils.CR, ' ');
			temp = StringUtils.replaceChars(temp, CharUtils.LF, ' ');
			sample.put("description", temp);
		}

		sample.put("organization.id", current.getOrganization().getId());

		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		String[] sortFields = request.getParameterValues("sort");
		String[] sortDirections = request.getParameterValues("dir");

		Page<Qualification> page = qualificationDAO.findByExample(sample, start, limit, sortFields, sortDirections);

		request.setAttribute("page", page);


		return "secure/organization/qualification-search";
	}

	/**
	 * Updates a qualification.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String updateQualification(final HttpServletRequest request, final HttpServletResponse response) {
		User current = getUser(request);
		Organization organization = current.getOrganization();

		String id = request.getParameter("id");

		int areaId = (id != null) ? Integer.parseInt(id) : 0;

		Qualification qualification;

		if(areaId > 0) {
			qualification = qualificationDAO.findById(areaId);
		} else {
			qualification = new Qualification();
		}

		String temp = request.getParameter("code");

		if(temp != null) {
			qualification.setCode(temp);

			Qualification otherQualification = qualificationDAO.findByCode(temp, organization.getId());

			if((otherQualification != null) && (otherQualification.getId() != areaId)) {
				request.setAttribute(Constants.ERRORS, "qualification.code.duplicated");

				return "secure/organization/qualification-update-error";
			}
		}

		temp = request.getParameter("description");
		temp = StringUtils.replaceChars(temp, CharUtils.CR, ' ');
		temp = StringUtils.replaceChars(temp, CharUtils.LF, ' ');
		qualification.setDescription(temp);
		qualification.setOrganization(organization);

		if(areaId > 0) {
			qualificationDAO.update(qualification);
		} else {
			qualificationDAO.save(qualification);
		}

		request.setAttribute("qualification", qualification);

		return "secure/organization/qualification-updated";
	}

	/**
	 * Retrieves the qualifications.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String getQualifications(final HttpServletRequest request, final HttpServletResponse response) {
		User current = getUser(request);

		String query = request.getParameter("query");

		List<Qualification> result;

		if((query != null) && (query.length() > 0)) {
			Map<String, Object> sample = new HashMap<String, Object>();

			// sample.put("code", query);
			sample.put("description", query);
			sample.put("organization.id", current.getOrganization().getId());

			result = qualificationDAO.findByExample(sample);
		} else {
			result = qualificationDAO.findByOrganization(current.getOrganization().getId());
		}


		request.setAttribute("result", result);

		return "secure/organization/qualifications";
	}

	/**
	 * Find associated units.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String findAssociatedUnits(final HttpServletRequest request, final HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));

		Map<String, Object> sample = new HashMap<String, Object>();

		sample.put("id", id);

		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		String[] sortFields = request.getParameterValues("sort");
		String[] sortDirections = request.getParameterValues("dir");


		Page<KnowledgeUnit> page = qualificationDAO.findAssociatedUnits(sample, start, limit, sortFields, sortDirections);

		request.setAttribute("page", page);

		return "secure/organization/units";
	}

	/**
	 * Find non-associated units.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String findNonAssociatedUnits(final HttpServletRequest request, final HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));

		Map<String, Object> sample = new HashMap<String, Object>();

		sample.put("id", id);

		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		String[] sortFields = request.getParameterValues("sort");
		String[] sortDirections = request.getParameterValues("dir");


		Page<KnowledgeUnit> page = qualificationDAO.findNonAssociatedUnits(
				sample, start, limit, sortFields, sortDirections);

		request.setAttribute("page", page);

		return "secure/organization/units";
	}

	/**
	 * Adds a unit.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String addUnit(final HttpServletRequest request, final HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		String[] units = request.getParameterValues("units");

		if(units != null) {
			Long[] unitIds = new Long[units.length];

			for(int i = 0; i < units.length; ++i) {
				unitIds[i] = Long.parseLong(units[i]);
			}

			Qualification qualification = qualificationDAO.findById(id);
			List<KnowledgeUnit> theUnits = knowledgeUnitDAO.findByIds(unitIds);

			qualification.getUnits().addAll(theUnits);
			qualificationDAO.update(qualification);
		}

		return "secure/organization/unit-added";
	}

	/**
	 * Removes a unit.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String removeUnit(final HttpServletRequest request, final HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		String[] units = request.getParameterValues("units");

		if(units != null) {
			Long[] unitIds = new Long[units.length];

			for(int i = 0; i < units.length; ++i) {
				unitIds[i] = Long.parseLong(units[i]);
			}

			Qualification qualification = qualificationDAO.findById(id);
			List<KnowledgeUnit> theUnits = knowledgeUnitDAO.findByIds(unitIds);

			qualification.getUnits().removeAll(theUnits);
			qualificationDAO.update(qualification);
		}

		return "secure/organization/unit-removed";
	}

	/**
	 * Checks remove qualifications.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String checkDeleteQualifications(final HttpServletRequest request, final HttpServletResponse response) {
		String[] qualifications = request.getParameterValues("elements");

		if(qualifications != null) {
			Integer[] qualificationIds = new Integer[qualifications.length];

			for(int i = 0; i < qualifications.length; ++i) {
				qualificationIds[i] = Integer.parseInt(qualifications[i]);
			}

			List theQualifications = qualificationDAO.getRemovalInformation(qualificationIds);

			request.setAttribute("qualifications", theQualifications);
		}

		return "secure/organization/qualifications-check-removed";
	}

	/**
	 * Remove qualifications.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String deleteQualifications(final HttpServletRequest request, final HttpServletResponse response) {
		String[] qualifications = request.getParameterValues("elements");

		if(qualifications != null) {
			Integer[] qualificationIds = new Integer[qualifications.length];

			for(int i = 0; i < qualifications.length; ++i) {
				qualificationIds[i] = Integer.parseInt(qualifications[i]);
			}

			qualificationDAO.remove(qualificationIds);
		}

		return "secure/organization/qualifications-removed";
	}
}
